package com.gitee.form_token.token;

import com.gitee.form_token.common.ValueUtil;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

@Slf4j
@Component
public class JwtUtil {

    // 生成 jwt
    public static String createToken(TokenDto tokenDto, String issuer) {
        HashMap<String, Object> claimMaps = new HashMap<>();
        claimMaps.put("user", tokenDto.getUser());
        claimMaps.put("uid", tokenDto.getUid() + "");
        claimMaps.put("rid", tokenDto.getRid() + "");

        // 构建 jwt
        JwtBuilder jwtBuilder = Jwts.builder();

        String jwtToken = jwtBuilder
                // Header
                .setHeaderParam("typ", "jwt")
                .setHeaderParam("alg", "HS256")
                // Payload
                .addClaims(claimMaps)
                .setSubject(tokenDto.getUser())
                .setId(UUID.randomUUID().toString())
                .setIssuer(issuer)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + ValueUtil.jwtExpire * 1000))
                .signWith(SignatureAlgorithm.HS256, ValueUtil.jwtSecret.getBytes())
                .compact();

        // log.info("jwtToken：{}", jwtToken);

        return jwtToken;
    }

    // 解析 jwt
    public static Claims getClaims(String jwt, String issuer) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(ValueUtil.jwtSecret.getBytes())
                    .parseClaimsJws(jwt)
                    .getBody();
            if (StrUtil.isBlank(issuer) || !claims.getIssuer().equals(issuer)) {
                return null;
            }
            return claims;
        } catch (ExpiredJwtException ex) {
            log.info("签名过期：{}", ex.getMessage());
            claims = ex.getClaims();
            return claims;
        } catch (MalformedJwtException | IllegalArgumentException | SignatureException ex) {
            log.info("格式或签名错误：{}", ex.getMessage());
            return null;
        } catch (Exception ex) {
            log.info("未知错误：{}", ex.getMessage());
            return null;
        }
    }

    // 是否过期
    public static boolean isExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }
}
